<?php
include_once('config/config.php');

$auth = isset($_COOKIE['auth']) ? json_decode($_COOKIE['auth'],true) : [];

if($auth)
{
    notice('您已登录，无须重复登录','index.php');
}

if($_POST)
{
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';

    if(empty($username))
    {
        notice('用户名不能为空');
    }

    if(empty($password))
    {
        notice('密码不能为空');
    }

    if(empty($code))
    {
        notice('验证码不能为空');
    }

    if($code != $_SESSION['code'])
    {
        notice('验证码错误');
    }

    $sql = "SELECT * FROM `pre_admin` WHERE `username` = '$username'";

    $admin = find($sql);

    if(!$admin)
    {
        notice('管理员不存在');
    }

    // 获取密码加密后的
    $password = md5($password . $admin['salt']);

    if($password != $admin['password'])
    {
        notice('密码错误');
    }

    // 不需要密码和密码盐
    unset($admin['password']);
    unset($admin['salt']);

    // 存储登录信息
    setcookie('auth',json_encode($admin));

    notice('登录成功','index.php');
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- 引入公共样式 -->
    <?php include_once('common/meta.php'); ?>
</head>

<body>

    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="index.php"><span class="second">Admin</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form method="post">
                        <label>用户名</label>
                        <input type="text" class="span12" name="username" placeholder="用户名">
                        
                        <label>密码</label>
                        <input type="password" class="span12" name="password" placeholder="密码">

                        <label>验证码</label>
                        <input type="text" class="span9" name="code" placeholder="验证码">
                        <img src="/config/imgcode.php" onclick="this.src = '/config/imgcode.php?id=' + Math.random()" alt="">

                        <div class="clearfix"></div>

                        <button class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>

</body>

</html>